package org.client.iot.ble;
import static android.net.wifi.WpsInfo.PBC;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Wi-Fi P2P 扫描工具类
 * 功能：检查权限 → 检查 Wi-Fi P2P 是否开启 → 扫描 P2P 设备 → 回调结果
 */

/**
 * Wi-Fi 扫描工具类
 * 功能：检查权限 → 检查 Wi-Fi 是否开启 → 扫描热点 → 回调结果
 */
public class WifiScanner {
    private static final String TAG = "WifiP2pScanner";

    /**
     * 扫描回调接口
     */
    public interface ScanCallback {
        void onScanStarted();
        void onScanResults(List<WifiP2pDevice> devices);
        void onScanFailed(String reason);
        void onP2pDisabled(); // Wi-Fi P2P 未开启
        void onConnectionInfoAvailable(WifiP2pInfo info); // 连接信息可用
    }

    private  Context context;
    private  WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel channel;
    private ScanCallback callback;
    private boolean isScanning = false;
    private boolean isRegistered = false;
    
    // 用于保存最近扫描的设备列表
    private List<WifiP2pDevice> deviceList = new ArrayList<>();

    // P2P扫描结果监听
    private final WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {
            handleScanResults(peerList);
        }
    };

    // P2P连接信息监听
    private final WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(@NonNull WifiP2pInfo info) {
            if (callback != null) {
                callback.onConnectionInfoAvailable(info);
            }
        }
    };

    // P2P状态变化广播接收器
    private final BroadcastReceiver p2pStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;

            switch (action) {
                case WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION:
                    // 检查Wi-Fi P2P是否开启
                    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        Log.d(TAG, "Wi-Fi P2P 已开启，重新尝试扫描");
                        startScanInternal();
                    } else {
                        Log.d(TAG, "Wi-Fi P2P 已关闭");
                        if (callback != null) {
                            callback.onP2pDisabled();
                        }
                    }
                    break;

                case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION:
                    // 当发现新设备时，请求更新设备列表
                    if (wifiP2pManager != null && channel != null) {
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                                != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        wifiP2pManager.requestPeers(channel, peerListListener);
                    }
                    break;

                case WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION:
                    // 连接状态已更改
                    if (wifiP2pManager != null && channel != null) {
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                                != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        wifiP2pManager.requestConnectionInfo(channel, connectionInfoListener);
                    }
                    break;
            }
        }
    };

    /**
     * 构造函数
     * @param context 上下文
     */
    public WifiScanner(@NonNull Context context) {
        this.context = context.getApplicationContext();
        this.wifiP2pManager = (WifiP2pManager) this.context.getSystemService(Context.WIFI_P2P_SERVICE);
        if (this.wifiP2pManager != null) {
            this.channel = this.wifiP2pManager.initialize(this.context, context.getMainLooper(), null);
        }
    }

    /**
     * 开始扫描P2P设备
     * @param callback 扫描回调
     */
    @RequiresPermission(allOf = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE
    })
    public void startScan(ScanCallback callback) {
        stop();
        this.callback = callback;

        if (!isLocationPermissionGranted()) {
            callback.onScanFailed("缺少位置权限，请授权后重试");
            return;
        }

        if (!isP2pSupported()) {
            callback.onScanFailed("设备不支持Wi-Fi P2P功能");
            return;
        }

        registerP2pReceiver();

        // 检查P2P状态
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            wifiP2pManager.requestP2pState(channel, new WifiP2pManager.P2pStateListener() {
                @Override
                public void onP2pStateAvailable(int state) {
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        startScanInternal();
                    } else {
                        callback.onP2pDisabled();
                    }
                }
            });
        }
    }

    /**
     * 内部扫描方法
     */
    private void startScanInternal() {
        if (isScanning || wifiP2pManager == null || channel == null) {
            return;
        }

        isScanning = true;
        if (callback != null) {
            callback.onScanStarted();
        }

        Log.d(TAG, "开始扫描Wi-Fi P2P设备");
        
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        
        wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "P2P设备发现请求已发送");
            }

            @Override
            public void onFailure(int reason) {
                isScanning = false;
                String errorMsg = "扫描失败，错误码: " + reason;
                Log.e(TAG, errorMsg);
                if (callback != null) {
                    callback.onScanFailed(errorMsg);
                }
            }
        });
    }

    /**
     * 处理扫描结果
     */
    private void handleScanResults(WifiP2pDeviceList peerList) {
        if (peerList == null) {
            if (callback != null) {
                callback.onScanFailed("扫描结果为空");
            }
            return;
        }

        Collection<WifiP2pDevice> devices = peerList.getDeviceList();
        deviceList.clear();
        deviceList.addAll(devices);

        Log.d(TAG, "P2P扫描完成，共发现 " + devices.size() + " 个设备");

        if (callback != null) {
            callback.onScanResults(new ArrayList<>(devices));
        }
    }

    /**
     * 连接到指定的P2P设备
     * @param device 要连接的设备
     * @param listener 连接结果监听器
     */
    @RequiresPermission(allOf = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE
    })
    public void connect(WifiP2pDevice device, WifiP2pManager.ActionListener listener) {
        if (wifiP2pManager == null || channel == null || device == null) {
            if (listener != null) {
                listener.onFailure(0);
            }
            return;
        }

        WifiP2pConfig config = new WifiP2pConfig();
        config.deviceAddress = device.deviceAddress;
        config.wps.setup = PBC;

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        wifiP2pManager.connect(channel, config, listener);
    }

    /**
     * 取消连接
     * @param listener 操作结果监听器
     */
    @RequiresPermission(allOf = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE
    })
    public void cancelConnect(WifiP2pManager.ActionListener listener) {
        if (wifiP2pManager == null || channel == null) {
            if (listener != null) {
                listener.onFailure(0);
            }
            return;
        }

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        wifiP2pManager.cancelConnect(channel, listener);
    }

    /**
     * 获取已发现的设备列表
     */
    public List<WifiP2pDevice> getDeviceList() {
        return new ArrayList<>(deviceList);
    }

    /**
     * 检查是否支持P2P功能
     */
    public boolean isP2pSupported() {
        return wifiP2pManager != null && channel != null;
    }

    /**
     * 检查位置权限是否已授予
     */
    private boolean isLocationPermissionGranted() {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 注册P2P广播接收器
     */
    private void registerP2pReceiver() {
        if (!isRegistered) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
            filter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
            filter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
            context.registerReceiver(p2pStateReceiver, filter);
            isRegistered = true;
        }
    }

    /**
     * 注销P2P广播接收器
     */
    private void unregisterP2pReceiver() {
        if (isRegistered) {
            try {
                context.unregisterReceiver(p2pStateReceiver);
            } catch (Exception e) {
                Log.e(TAG, "unregisterP2pReceiver error", e);
            }
            isRegistered = false;
        }
    }

    /**
     * 停止扫描，清理资源
     */
    public void stop() {
        if (wifiP2pManager != null && channel != null && isScanning) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            wifiP2pManager.stopPeerDiscovery(channel, null);
        }
        isScanning = false;
        unregisterP2pReceiver();
        callback = null;
    }

    /**
     * 获取设备状态的可读文本
     */
    public static String getDeviceStatus(int statusCode) {
        switch (statusCode) {
            case WifiP2pDevice.AVAILABLE:
                return "可用";
            case WifiP2pDevice.INVITED:
                return "已邀请";
            case WifiP2pDevice.CONNECTED:
                return "已连接";
            case WifiP2pDevice.FAILED:
                return "失败";
            case WifiP2pDevice.UNAVAILABLE:
                return "不可用";
            default:
                return "未知";
        }
    }
}
